package com.d3works.apps.stock.web;

import com.d3works.apps.base.callable.ControllerCallableTool;
import com.d3works.apps.base.db.Batch;
import com.d3works.apps.stock.db.StockBatch;
import com.d3works.apps.stock.db.repo.StockBatchRepository;
import com.d3works.apps.stock.service.batch.StockBatchService;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;

@Singleton
public class StockBatchController {

  public void runBatch(ActionRequest request, ActionResponse response) {
    try {
      StockBatch stockBatch = request.getContext().asType(StockBatch.class);
      StockBatchService stockBatchService = Beans.get(StockBatchService.class);
      stockBatchService.setBatchModel(
          Beans.get(StockBatchRepository.class).find(stockBatch.getId()));
      ControllerCallableTool<Batch> controllerCallableTool = new ControllerCallableTool<>();

      Batch batch = controllerCallableTool.runInSeparateThread(stockBatchService, response);

      if (batch != null) {
        response.setInfo(batch.getComments());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    } finally {
      response.setReload(true);
    }
  }
}
